package service

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	"hanlinyuan_qa/ip"
	"hanlinyuan_qa/model"
	"hanlinyuan_qa/util"
	"net/http"
	"time"
)

type GetQuestionValidator struct {
	QuestionID string `form:"qid" binding:"required"`
}

func GetQuestion(c *gin.Context) {
	var getQuestionValidator GetQuestionValidator
	if err := c.ShouldBind(&getQuestionValidator); err == nil {
		qid := getQuestionValidator.QuestionID
		var data []model.Question
		model.GetDB().Model(data).Where("question_id=?", qid).Find(&data)
		//  model.GetDB().Where("question_id=?", tmpData[0].QuestionID).Updates(&tmpData[0])
		if len(data) == 0 {
			c.JSON(http.StatusOK, gin.H{
				"msg":  "未找到对应的问卷",
				"code": 0,
				"data": "",
			})
			return
		}
		if data[0].IsDelete {
			c.JSON(http.StatusOK, gin.H{
				"msg":  "问卷已被删除",
				"code": 0,
				"data": "",
			})
			return
		}
		if !data[0].IsActivate {
			c.JSON(http.StatusOK, gin.H{
				"msg":  "问卷已截止",
				"code": 0,
				"data": "",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code":    1,
			"qid":     data[0].QuestionID,
			"content": data[0].Content,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"msg":  err.Error(),
			"code": 0,
			"data": gin.H{},
		})
	}
}

// 自定义验证函数，验证邮件的格式
func check(fl validator.FieldLevel) bool {
	content := fl.Field().String()
	return isValidJSON(content)
}

type AnswerValidator struct {
	QuestionID string `form:"qid" binding:"required"`
	Content    string `form:"content" binding:"required,check"`
}

func UploadAnswer(c *gin.Context) {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		_ = v.RegisterValidation("check", check)
	}
	var answerValidator AnswerValidator
	if err := c.ShouldBind(&answerValidator); err == nil {
		qid := answerValidator.QuestionID
		content := answerValidator.Content
		var tmpData []model.Question
		model.GetDB().Model(tmpData).Where("question_id=?", qid).Find(&tmpData)
		if len(tmpData) == 0 {
			c.JSON(http.StatusOK, gin.H{
				"msg":  "未找到对应的问卷",
				"code": 0,
				"data": "",
			})
			return
		}
		if tmpData[0].IsActivate == false {
			c.JSON(http.StatusOK, gin.H{
				"msg":  "问卷已截止收集",
				"code": 0,
				"data": "",
			})
			return
		}
		if tmpData[0].IsDelete == true {
			c.JSON(http.StatusOK, gin.H{
				"msg":  "问卷已被删除",
				"code": 0,
				"data": "",
			})
			return
		}

		if !util.IsValidSurvey(content) {
			println("问卷失效了")
			c.JSON(http.StatusOK, gin.H{
				"msg":  "问卷是无效的",
				"code": 0,
				"data": "",
			})
			return
		}

		var tmpAnswer model.Answer
		tmpAnswer.QuestionID = qid
		tmpAnswer.IpAddress = c.ClientIP()
		tmpAnswer.IpLocation = ip.GetIpLocation(c.ClientIP())
		tmpAnswer.Content = content
		tmpAnswer.UpdateTime = time.Now()
		tmpAnswer.CreateTime = time.Now()
		tmpAnswer.IsDelete = false

		jsonString, _ := json.Marshal(tmpAnswer)
		currentTime := time.Now()
		dateSuffix := currentTime.Format("20060102") // 格式化为年月日，例如20231106
		util.BackUp(string(jsonString), fmt.Sprintf("answer_%s.txt", dateSuffix))

		tmpData[0].Count++
		model.GetDB().Where("question_id=?", tmpData[0].QuestionID).Updates(&tmpData[0])
		model.GetDB().Create(&tmpAnswer)
		c.JSON(http.StatusOK, tmpAnswer)
	} else {
		c.JSON(http.StatusOK, gin.H{
			"msg":  err.Error(),
			"code": 0,
			"data": gin.H{},
		})
	}
}

func isValidJSON(input string) bool {
	var jsonMap map[string]interface{}
	err := json.Unmarshal([]byte(input), &jsonMap)
	return err == nil
}

type UpdateQuestionValidator struct {
	QuestionID string `form:"qid" binding:"required"`
	Content    string `form:"content" binding:"required,check"`
	IsActivate string `form:"is_activate" binding:"required"`
}

func UpdateQuestion(c *gin.Context) {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		_ = v.RegisterValidation("check", check)
	}

	var val UpdateQuestionValidator
	if err := c.ShouldBind(&val); err == nil {
		var dataQuestion []model.Question
		model.GetDB().Model(dataQuestion).Where("question_id=?", val.QuestionID).Find(&dataQuestion)
		if len(dataQuestion) == 0 {
			c.JSON(http.StatusOK, gin.H{
				"data": "",
				"msg":  "未查找到对应的问卷",
				"code": 0,
			})
			return
		}
		model.GetDB().Model(dataQuestion).Where("question_id=?", dataQuestion[0].QuestionID).Updates(
			map[string]interface{}{
				"update_time": time.Now(),
				"is_activate": val.IsActivate == "true",
				"content":     val.Content,
			},
		)
		c.JSON(http.StatusOK, gin.H{
			"data": "",
			"msg":  "更新成功！",
			"code": 1,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"msg":  err.Error(),
			"code": 0,
			"data": gin.H{},
		})
	}

}

func CreateQuestion(c *gin.Context) {
	content := c.PostForm("content")
	if isValidJSON(content) {
		var tmpData model.Question
		tmpData.QuestionID = util.GetUniqueID()
		tmpData.CreateTime = time.Now()
		tmpData.UpdateTime = time.Now()
		tmpData.Count = 0
		tmpData.IsActivate = true
		tmpData.IsDelete = false
		tmpData.Content = content

		jsonString, _ := json.Marshal(tmpData)
		currentTime := time.Now()
		dateSuffix := currentTime.Format("20060102") // 格式化为年月日，例如20231106
		util.BackUp(string(jsonString), fmt.Sprintf("question_%s.txt", dateSuffix))

		model.GetDB().Create(&tmpData)
		c.JSON(http.StatusOK, gin.H{
			"data": gin.H{
				"qid": tmpData.QuestionID,
			},
			"msg":  "创建成功！",
			"code": 1,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"data": "",
			"msg":  "非JSON格式",
			"code": 0,
		})
	}
}
